<template>
  <Head title="发放优惠券" />
  <AdminLayout title="发放优惠券" :subtitle="`${coupon.name} (${coupon.code})`">
    <template #actions>
      <Link :href="route('admin.coupons.index')" 
            class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
        ← 返回列表
      </Link>
    </template>

    <div class="space-y-6">
      <!-- 优惠券信息卡片 -->
      <div class="bg-white rounded-2xl p-6 shadow-sm">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900">优惠券信息</h3>
          <div class="flex items-center space-x-2">
            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                  :class="coupon.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
              {{ coupon.is_active ? '启用中' : '已禁用' }}
            </span>
          </div>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">优惠券代码</label>
            <p class="text-sm font-mono text-gray-900 bg-gray-50 px-2 py-1 rounded">{{ coupon.code }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">优惠券类型</label>
            <p class="text-sm text-gray-900">{{ getCouponTypeText(coupon.type) }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">优惠券面值</label>
            <p class="text-sm text-gray-900">{{ formatCouponValue(coupon) }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">使用条件</label>
            <p class="text-sm text-gray-900">
              {{ coupon.min_spend ? `满${formatPrice(coupon.min_spend)}可用` : '无门槛' }}
            </p>
          </div>
        </div>
      </div>

      <!-- 用户统计信息 -->
      <div class="bg-white rounded-2xl p-6 shadow-sm">
        <h3 class="text-lg font-semibold text-gray-900 mb-6">用户统计</h3>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div class="text-center">
            <div class="text-2xl font-bold text-gray-900">{{ userStats?.total_users || 0 }}</div>
            <div class="text-sm text-gray-500">总用户数</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-green-600">{{ userStats?.active_users || 0 }}</div>
            <div class="text-sm text-gray-500">活跃用户</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-blue-600">{{ userStats?.recent_users || 0 }}</div>
            <div class="text-sm text-gray-500">新用户(30天)</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-purple-600">{{ userStats?.vip_users || 0 }}</div>
            <div class="text-sm text-gray-500">VIP用户</div>
          </div>
        </div>
      </div>

      <!-- 发放方式选择 -->
      <div class="bg-white rounded-2xl p-6 shadow-sm">
        <h3 class="text-lg font-semibold text-gray-900 mb-6">发放方式</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
               :class="distributionMethod === 'manual' ? 'border-gray-900 bg-gray-50' : ''"
               @click="distributionMethod = 'manual'">
            <input id="manual" v-model="distributionMethod" type="radio" value="manual" 
                   class="h-4 w-4 text-gray-900 focus:ring-gray-900">
            <label for="manual" class="ml-3 flex-1">
              <div class="text-sm font-medium text-gray-900">手动选择用户</div>
              <div class="text-sm text-gray-500">精确选择特定用户</div>
            </label>
            <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
            </svg>
          </div>
          
          <div class="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
               :class="distributionMethod === 'bulk' ? 'border-gray-900 bg-gray-50' : ''"
               @click="distributionMethod = 'bulk'">
            <input id="bulk" v-model="distributionMethod" type="radio" value="bulk" 
                   class="h-4 w-4 text-gray-900 focus:ring-gray-900">
            <label for="bulk" class="ml-3 flex-1">
              <div class="text-sm font-medium text-gray-900">批量发放</div>
              <div class="text-sm text-gray-500">所有活跃用户</div>
            </label>
            <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
            </svg>
          </div>

          <div class="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
               :class="distributionMethod === 'filter' ? 'border-gray-900 bg-gray-50' : ''"
               @click="distributionMethod = 'filter'">
            <input id="filter" v-model="distributionMethod" type="radio" value="filter" 
                   class="h-4 w-4 text-gray-900 focus:ring-gray-900">
            <label for="filter" class="ml-3 flex-1">
              <div class="text-sm font-medium text-gray-900">条件筛选</div>
              <div class="text-sm text-gray-500">按条件筛选用户</div>
            </label>
            <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.207A1 1 0 013 6.5V4z"></path>
            </svg>
          </div>
        </div>
      </div>

      <!-- 手动发放表单 -->
      <div v-if="distributionMethod === 'manual'" class="bg-white rounded-2xl p-6 shadow-sm">
        <h3 class="text-lg font-semibold text-gray-900 mb-6">选择用户</h3>
        
        <!-- 用户搜索 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索用户</label>
          <div class="relative">
            <input v-model="searchQuery" type="text" 
                   class="w-full px-4 py-2 pl-10 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                   placeholder="输入用户名、邮箱或手机号">
            <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
          </div>
        </div>

        <!-- 用户列表 -->
        <div class="mb-6">
          <div class="flex items-center justify-between mb-4">
            <h4 class="text-sm font-medium text-gray-700">用户列表</h4>
            <span class="text-sm text-gray-500">已选择 {{ selectedUsers.length }} 个用户</span>
          </div>
          
          <div class="max-h-64 overflow-y-auto border border-gray-200 rounded-lg">
            <div v-if="filteredUsers.length === 0" class="p-4 text-center text-gray-500">
              没有找到用户
            </div>
            <div v-else class="divide-y divide-gray-200">
              <div v-for="user in filteredUsers" :key="user.id" 
                   class="flex items-center p-3 hover:bg-gray-50 cursor-pointer"
                   @click="toggleUser(user)">
                <input :id="`user-${user.id}`" 
                       :checked="selectedUsers.includes(user.id)"
                       type="checkbox" 
                       class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded">
                <label :for="`user-${user.id}`" class="ml-3 flex-1 cursor-pointer">
                  <div class="flex items-center justify-between">
                    <div>
                      <div class="text-sm font-medium text-gray-900">{{ user.name || '未设置' }}</div>
                      <div class="text-sm text-gray-500">{{ user.email }}</div>
                    </div>
                    <div class="text-xs text-gray-400">
                      {{ formatDate(user.created_at) }}
                      <span v-if="user.email_verified_at" class="ml-1 text-green-500">✓</span>
                    </div>
                  </div>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 发放数量 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">每个用户发放数量</label>
            <input v-model.number="quantity" type="number" min="1" max="10" 
                   class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
            <p class="mt-1 text-sm text-gray-500">每个用户最多发放10张</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">发放说明</label>
            <input v-model="notes" type="text" 
                   class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                   placeholder="可选，用于记录发放原因">
          </div>
        </div>
      </div>

      <!-- 批量发放设置 -->
      <div v-if="distributionMethod === 'bulk'" class="bg-white rounded-2xl p-6 shadow-sm">
        <h3 class="text-lg font-semibold text-gray-900 mb-6">批量发放设置</h3>
        <div class="space-y-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">每个用户发放数量</label>
            <input v-model.number="bulkQuantity" type="number" min="1" max="5" 
                   class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
            <p class="mt-1 text-sm text-gray-500">每个用户最多发放5张</p>
          </div>
          
          <div class="rounded-lg bg-amber-50 p-4 border border-amber-200">
            <div class="flex">
              <div class="flex-shrink-0">
                <svg class="h-5 w-5 text-amber-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                </svg>
              </div>
              <div class="ml-3">
                <h3 class="text-sm font-medium text-amber-800">重要提醒</h3>
                <div class="mt-2 text-sm text-amber-700">
                  <p>批量发放将给所有活跃用户发放优惠券，此操作不可撤销，请谨慎操作。</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 条件筛选表单 -->
      <div v-if="distributionMethod === 'filter'" class="bg-white rounded-2xl p-6 shadow-sm">
        <h3 class="text-lg font-semibold text-gray-900 mb-6">筛选条件</h3>
        <div class="space-y-6">
          <!-- 用户类型 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">用户类型</label>
            <select v-model="filters.user_type" 
                    class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
              <option value="">全部用户</option>
              <option value="active">活跃用户</option>
              <option value="recent">新用户(30天内)</option>
              <option value="vip">VIP用户(有订单)</option>
            </select>
          </div>

          <!-- 注册时间范围 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">注册开始时间</label>
              <input v-model="filters.registration_date_from" type="date" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">注册结束时间</label>
              <input v-model="filters.registration_date_to" type="date" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
            </div>
          </div>

          <!-- 消费金额范围 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">最低消费金额</label>
              <input v-model.number="filters.min_order_amount" type="number" min="0" step="0.01" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                     placeholder="0.00">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">最高消费金额</label>
              <input v-model.number="filters.max_order_amount" type="number" min="0" step="0.01" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                     placeholder="不限">
            </div>
          </div>

          <!-- 地区筛选 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">省份</label>
              <input v-model="filters.province" type="text" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                     placeholder="如：北京市">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">城市</label>
              <input v-model="filters.city" type="text" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                     placeholder="如：朝阳区">
            </div>
          </div>

          <!-- 发放设置 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">每个用户发放数量</label>
              <input v-model.number="quantity" type="number" min="1" max="5" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
              <p class="mt-1 text-sm text-gray-500">每个用户最多发放5张</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">发放说明</label>
              <input v-model="notes" type="text" 
                     class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                     placeholder="可选，用于记录发放原因">
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end space-x-4 pt-6 border-t border-gray-200">
        <Link :href="route('admin.coupons.index')" 
              class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
          取消
        </Link>
        <button @click="submitDistribution" 
                :disabled="isSubmitting"
                class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-900 focus:ring-offset-2 disabled:opacity-50">
          {{ isSubmitting ? '发放中...' : '确认发放' }}
        </button>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'

const props = defineProps({
  coupon: {
    type: Object,
    required: true
  },
  userStats: {
    type: Object,
    default: () => ({})
  },
  users: {
    type: Array,
    default: () => []
  }
})


const distributionMethod = ref('manual')
const searchQuery = ref('')
const selectedUsers = ref([])
const quantity = ref(1)
const bulkQuantity = ref(1)
const notes = ref('')
const isSubmitting = ref(false)

// 筛选条件
const filters = ref({
  user_type: '',
  registration_date_from: '',
  registration_date_to: '',
  min_order_amount: null,
  max_order_amount: null,
  province: '',
  city: ''
})

const getCouponTypeText = (type) => {
  const types = {
    fixed: '固定金额',
    percentage: '百分比折扣',
    free_shipping: '免运费',
    threshold: '满减券'
  }
  return types[type] || type
}

const formatCouponValue = (coupon) => {
  switch (coupon.type) {
    case 'fixed':
      return `¥${coupon.value}`
    case 'percentage':
      return `${coupon.value}%`
    case 'free_shipping':
      return '免运费'
    case 'threshold':
      return `满${coupon.value}减${coupon.max_discount || coupon.value}`
    default:
      return coupon.value
  }
}

const formatPrice = (price) => {
  return `¥${Number(price).toFixed(2)}`
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 过滤用户列表
const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return props.users
  }
  
  const query = searchQuery.value.toLowerCase()
  return props.users.filter(user => 
    user.name?.toLowerCase().includes(query) ||
    user.email?.toLowerCase().includes(query) ||
    user.phone?.includes(query)
  )
})

// 切换用户选择
const toggleUser = (user) => {
  const index = selectedUsers.value.indexOf(user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(user.id)
  }
}

const submitDistribution = () => {
  // 验证表单
  if (distributionMethod.value === 'manual' && selectedUsers.value.length === 0) {
    alert('请选择要发放的用户')
    return
  }

  if (distributionMethod.value === 'filter' && !filters.value.user_type && 
      !filters.value.registration_date_from && !filters.value.min_order_amount) {
    alert('请至少设置一个筛选条件')
    return
  }

  isSubmitting.value = true

  const data = {
    distribution_method: distributionMethod.value,
    quantity: distributionMethod.value === 'bulk' ? bulkQuantity.value : quantity.value,
    notes: notes.value
  }

  if (distributionMethod.value === 'manual') {
    data.user_ids = selectedUsers.value
  } else if (distributionMethod.value === 'filter') {
    data.filters = filters.value
  }

  router.post(route('admin.coupons.send-to-users', props.coupon.id), data, {
    onSuccess: () => {
      router.visit(route('admin.coupons.index'))
    },
    onFinish: () => {
      isSubmitting.value = false
    }
  })
}
</script>
